<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Programming in Lua : 20.4</title>
<link rel="stylesheet" type="text/css" href="pil.css">
</head>
<body>
<p class="warning">
<A HREF="contents.html"><IMG TITLE="Programming in Lua (first edition)" SRC="capa.jpg" ALT="" ALIGN="left"></A>This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.<BR>The third edition targets Lua 5.2 and is available at <A HREF="http://www.amazon.com/exec/obidos/ASIN/859037985X/theprogrammil3-20">Amazon</A> and other bookstores.<BR>By buying the book, you also help to <A HREF="../donations.html">support the Lua project</A>.
</p>
<table width="100%" class="nav">
<tr>
<td width="10%" align="left"><a href="20.3.html"><img border="0" src="left.png" alt="Previous"></a></td>
<td width="80%" align="center"><a href="contents.html"><font face="Helvetica,Arial,sanserif">
<font color="gray">Programming in </font><font color="blue"> Lua</font>
</font></a></td>
<td width="10%" align="right"><a href="21.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
<tr>
<td width="10%" align="left"></td>
<td width="80%" align="center"><a href="contents.html#P3">Part III. The Standard Libraries</a>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a href="contents.html#20">Chapter 20. The String Library</a></td>
<td width="10%" align="right"></td></tr>
</table>
<hr/>
<p><h2>20.4 &ndash; Tricks of the Trade</h2>

<p>Pattern matching is a powerful tool for manipulating strings.
You can perform many complex operations with only a few
calls to <code>string.gsub</code> and <code>find</code>.
However, as with any power, you must use it carefully.

<p>Pattern matching is not a replacement for a proper parser.
For quick-and-dirty programs,
you can do useful manipulations on source code,
but it is hard to build a product with quality.
As a good example, consider the pattern we used to match
comments in a C program:
'<code>/%*.-%*/</code>'.
If your program has a string containing <code>"/*"</code>,
you will get a wrong result:
<pre>
    test = [[char s[] = "a /* here";  /* a tricky string */]]
    print(string.gsub(test, "/%*.-%*/", "&lt;COMMENT>"))
      --> char s[] = "a &lt;COMMENT>
</pre>
Strings with such contents are rare
and, for your own use, that pattern will probably do its job.
But you cannot sell a program with such a flaw.

<p>Usually, pattern matching is efficient enough for Lua programs:
A Pentium 333MHz
(which is not a fast machine by today's standards)
takes less than a tenth of a second to
match all words in a text with 200K characters (30K words).
But you can take precautions.
You should always make the pattern as specific as possible;
loose patterns are slower than specific ones.
An extreme example is '<code>(.-)%$</code>',
to get all text in a string up to the first dollar sign.
If the subject string has a dollar sign,
everything goes fine;
but suppose that the string does not contain any dollar signs.
The algorithm will first try to match the pattern starting at the
first position of the string.
It will go through all the string, looking for a dollar.
When the string ends, the pattern fails
<em>for the first position</em> of the string.
Then, the algorithm will do the whole search again,
starting at the second position of the string,
only to discover that the pattern does not match there, too;
and so on.
This will take a quadratic time,
which results in more than three hours
in a Pentium 333MHz for a string with 200K characters.
You can correct this problem simply by anchoring the pattern at
the first position of the string, with '<code>^(.-)%$</code>'.
The anchor tells the algorithm to stop the search if it cannot find
a match at the first position.
With the anchor, the pattern runs in less than a tenth of a second.

<p>Beware also of <em>empty</em> patterns,
that is, patterns that match the empty string.
For instance, if you try to match names with a pattern like
'<code>%a*</code>', you will find names everywhere:
<pre>
    i, j = string.find(";$%  **#$hello13", "%a*")
    print(i,j)   --> 1  0
</pre>
In this example,
the call to <code>string.find</code> has correctly found an empty sequence of
letters at the beginning of the string.

<p>It never makes sense to write a pattern that begins
or ends with the modifier `<code>-</code>&acute;,
because it will match only the empty string.
This modifier always needs something around it,
to anchor its expansion.
Similarly,
a pattern that includes '<code>.*</code>' is tricky,
because this construction can expand much more than you intended.

<p>Sometimes, it is useful to use Lua itself to build a pattern.
As an example, let us see how we can find long lines in a text,
say lines with more than 70 characters.
Well, a long line is a sequence of 70 or more characters
different from newline.
We can match a single character different from newline
with the character class '<code>[^\n]</code>'.
Therefore, we can match a long line with a pattern that repeats
70 times the pattern for one character,
followed by zero or more of those characters.
Instead of writing this pattern by hand,
we can create it with <code>string.rep</code>:
<pre>
    pattern = string.rep("[^\n]", 70) .. "[^\n]*"
</pre>

<p>As another example,
suppose you want to make a
case-insensitive search.
A way to do that is to change any letter <em>x</em> in the pattern
for the class '<code>[<em>xX</em>]</code>', that is, a class including both the
upper and the lower versions of the original letter.
We can automate that conversion with a function:
<pre>
    function nocase (s)
      s = string.gsub(s, "%a", function (c)
            return string.format("[%s%s]", string.lower(c),
                                           string.upper(c))
          end)
      return s
    end
    
    print(nocase("Hi there!"))
      -->  [hH][iI] [tT][hH][eE][rR][eE]!
</pre>

<p>Sometimes, you want to change every plain occurrence
of <code>s1</code> to <code>s2</code>,
without regarding any character as magic.
If the strings <code>s1</code> and <code>s2</code> are literals,
you can add proper escapes to
magic characters while you write the strings.
But if those strings are variable values, you can use another
<code>gsub</code> to put the escapes for you:
<pre>
    s1 = string.gsub(s1, "(%W)", "%%%1")
    s2 = string.gsub(s2, "%%", "%%%%")
</pre>
In the search string, we escape all non-alphanumeric characters.
In the replacement string, we escape only the `<code>%</code>&acute;.

<p>Another useful technique for pattern matching is to
pre-process the subject string before the real work.
A simple example of the use of pre-processing is to
change to upper case all quoted strings in a text,
where a quoted string starts and ends with a double quote (`<code>"</code>&acute;),
but may contain escaped quotes (<code>"\""</code>):
<pre>
    follows a typical string: "This is \"great\"!".
</pre>
Our approach to handling such cases is to pre-process the text so as
to encode the problematic sequence to something else.
For instance, we could code <code>"\""</code> as <code>"\1"</code>.
However, if the original text already contains a <code>"\1"</code>,
we are in trouble.
An easy way to do the encoding and avoid this problem is to
code all sequences <code>"\<em>x</em>"</code> as <code>"\<em>ddd</em>"</code>,
where <em>ddd</em> is the decimal representation of the character <em>x</em>:
<pre>
    function code (s)
      return (string.gsub(s, "\\(.)", function (x)
                return string.format("\\%03d", string.byte(x))
              end))
    end
</pre>
Now any sequence <code>"\<em>ddd</em>"</code> in the encoded string must have come
from the coding,
because any <code>"\<em>ddd</em>"</code> in the original string has been coded, too.
So the decoding is an easy task:
<pre>
    function decode (s)
      return (string.gsub(s, "\\(%d%d%d)", function (d)
                return "\\" .. string.char(d)
              end))
    end
</pre>

<p>Now we can complete our task.
As the encoded string does not contain any escaped quote (<code>"\""</code>),
we can search for quoted strings simply with '<code>".-"</code>':
<pre>
    s = [[follows a typical string: "This is \"great\"!".]]
    s = code(s)
    s = string.gsub(s, '(".-")', string.upper)
    s = decode(s)
    print(s)
      --> follows a typical string: "THIS IS \"GREAT\"!".
</pre>
or, in a more compact notation,
<pre>
    print(decode(string.gsub(code(s), '(".-")', string.upper)))
</pre>

<p>As a more complex task,
let us return to our example of a primitive format converter,
which changes format commands written as <code>\command{string}</code> to
XML style:
<pre>
    &lt;command>string&lt;/command>
</pre>
But now our original format is more powerful
and uses the backslash character as a general escape,
so that we can represent the characters `<code>\</code>&acute;,
`<code>{</code>&acute;, and `<code>}</code>&acute;,
writing <code>"\\"</code>, <code>"\{"</code>, and <code>"\}"</code>.
To avoid our pattern matching mixing up commands and escaped characters,
we should recode those sequences in the original string.
However, this time we cannot code all sequences <code>\<em>x</em></code>,
because that would code our commands (written as <code>\command</code>) too.
Instead, we code <code>\<em>x</em></code> only when <em>x</em> is not a letter:
<pre>
    function code (s)
      return (string.gsub(s, '\\(%A)', function (x)
               return string.format("\\%03d", string.byte(x))
             end))
    end
</pre>
The <code>decode</code> is like that of the previous example,
but it does not include the backslashes in the final string;
therefore, we can call <code>string.char</code> directly:
<pre>
    function decode (s)
      return (string.gsub(s, '\\(%d%d%d)', string.char))
    end
    
    s = [[a \emph{command} is written as \\command\{text\}.]]
    s = code(s)
    s = string.gsub(s, "\\(%a+){(.-)}", "&lt;%1>%2&lt;/%1>")
    print(decode(s))
      -->  a &lt;emph>command&lt;/emph> is written as \command{text}.
</pre>

<p>Our last example here deals with <em>Comma-Separated Values</em> (CSV),
a text format supported by many programs,
such as Microsoft Excel, to represent tabular data.
A CSV file represents a list of records,
where each record is a list of string values written in a single line,
with commas between the values.
Values that contain commas
must be written between double quotes;
if such values also have quotes, the quotes are written as two quotes.
As an example, the array
<pre>
    {'a b', 'a,b', ' a,"b"c', 'hello "world"!', ''}
</pre>
can be represented as
<pre>
    a b,"a,b"," a,""b""c", hello "world"!,
</pre>
To transform an array of strings into CSV is easy.
All we have to do is to concatenate the strings with
commas between them:
<pre>
    function toCSV (t)
      local s = ""
      for _,p in pairs(t) do
        s = s .. "," .. escapeCSV(p)
      end
      return string.sub(s, 2)      -- remove first comma
    end
</pre>
If a string has commas or quotes inside,
we enclose it between quotes and escape its original quotes:
<pre>
    function escapeCSV (s)
      if string.find(s, '[,"]') then
        s = '"' .. string.gsub(s, '"', '""') .. '"'
      end
      return s
    end
</pre>

<p>To break a CSV into an array is more difficult,
because we must avoid mixing up the commas written between quotes
with the commas that separate fields.
We could try to escape the commas between quotes.
However, not all quote characters act as quotes;
only quote characters after a comma act as a starting quote,
as long as the comma itself is acting as a comma
(that is, it is not between quotes).
There are too many subtleties.
For instance, two quotes may represent a single quote,
two quotes, or nothing:
<pre>
    "hello""hello", "",""
</pre>
The first field in this example is the string <code>"hello"hello"</code>,
the second field is the string <code>" """</code>
(that is, a space followed by two quotes),
and the last field is an empty string.

<p>We could try to use multiple <code>gsub</code> calls to handle
all those cases,
but it is easier to program this task with a more conventional approach,
using an explicit loop over the fields.
The main task of the loop body is to find the next comma;
it also stores the field contents in a table.
For each field,
we explicitly test whether the field starts with a quote.
If it does, we do a loop looking for the closing quote.
In this loop, we use the pattern '<code>"("?)</code>'
to find the closing quote of a field:
If a quote is followed by another quote,
the second quote is captured and assigned to the <code>c</code> variable,
meaning that this is not the closing quote yet.
<pre>
    function fromCSV (s)
      s = s .. ','        -- ending comma
      local t = {}        -- table to collect fields
      local fieldstart = 1
      repeat
        -- next field is quoted? (start with `"'?)
        if string.find(s, '^"', fieldstart) then
          local a, c
          local i  = fieldstart
          repeat
            -- find closing quote
            a, i, c = string.find(s, '"("?)', i+1)
          until c ~= '"'    -- quote not followed by quote?
          if not i then error('unmatched "') end
          local f = string.sub(s, fieldstart+1, i-1)
          table.insert(t, (string.gsub(f, '""', '"')))
          fieldstart = string.find(s, ',', i) + 1
        else                -- unquoted; find next comma
          local nexti = string.find(s, ',', fieldstart)
          table.insert(t, string.sub(s, fieldstart, nexti-1))
          fieldstart = nexti + 1
        end
      until fieldstart > string.len(s)
      return t
    end
    
    t = fromCSV('"hello "" hello", "",""')
    for i, s in ipairs(t) do print(i, s) end
      --> 1       hello " hello
      --> 2        ""
      --> 3
</pre>

<p>
<hr/>
<table width="100%" class="nav">
<tr valign="top">
<td width="90%" align="left">
<small>
  Copyright &copy; 2003&ndash;2004 Roberto Ierusalimschy.  All rights reserved.
</small>
</td>
<td width="10%" align="right"><a href="21.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
</table>


</body></html>

